package nature.nano.control.script.run.message;

import java.util.ArrayList;
import java.util.List;

import nature.nano.component.EmptyProps;
import nature.nano.component.PrimaryPipe;
import nature.nano.component.Strings;
import nature.nano.iface.Accepter;
import nature.nano.iface.Props;
import nature.nano.iface.secondary.Startable;

public class RunningMessager extends PrimaryPipe implements Startable {

	private List<Props> errors = new ArrayList<Props>();
	private int count = 0;
	private int max = -1;
	
	public RunningMessager() {
		props("max-errors");
	}
	
	@Override
	public void anBegin(String type, Props props) {
		if (type.equals(Strings.error)) {
			if (errors.size() < getMaxErrors()) {
				errors.add(props);
			}
			count++;
		}
	}

	private int getMaxErrors() {
		if (max < 0) {
			max = intProp("max-errors", 3);
		}
		return max;
	}

	@Override
	public void start() {
		if (errors.size() == 0) {
			return;
		}
		
		Accepter accepter = slot(Strings.output);

		accepter.onBegin("RUNNING", EmptyProps.instance);

		if (count > errors.size()) {
			accepter.onContent(count + " errors, using builtin object \"Errors\" to check out");
		}
		
		for (Props prop : errors) {
			accepter.onBegin("Runtime-Error", prop);
			accepter.onEnd("Runtime-Error");							
		}	
		
		if (count > errors.size()) {
			accepter.onContent("...");
		}
		
		accepter.onEnd("RUNNING");
	}
	
}
